<template>
  <div class="env-bg">

    <el-card class="env-card" :body-style="{ padding: '20px' }">
      <span class="card-title">历史仿真记录</span>
      <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" label-width="100px">
        <el-form-item label="仿真名称" prop="keyword">
          <el-input v-model="queryParams.keyword" placeholder="请输入仿真名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleQuery">
           <el-icon><Search /> </el-icon> 搜索
          </el-button>
          <el-button size="small" @click="resetQuery">
            <el-icon><Refresh /> </el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" :key="selectedId" style="width: 100%" stripe>
        <el-table-column label="仿真ID" width="150" align="center">
          <template #default="{ row }">
            <el-radio :label="row.simulation_id" v-model="selectedId" @click="handleRadioClick(row.simulation_id)" />
          </template>
        </el-table-column>
        <el-table-column prop="env_param_id" label="仿真环境ID" width="150" align="center" />
        <el-table-column prop="name" label="仿真名称" align="center" />
        <el-table-column prop="created_at" label="仿真时间" align="center" />
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <div style="display: flex; gap: 8px;">
              <el-button
                  size="small"
                  type="primary"
                  @click="goToScreen(scope.row)">
                大屏查看仿真结果
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="deleteSimulate(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :total="total" layout="prev, pager, next"
        class="pagination" />
      <el-button type="primary" class="export-btn" @click="exportExcel" :disabled="!selectedId">
          <el-icon><Download /></el-icon> 导出
      </el-button>
      <!-- 吸顶卡片，仅在选中仿真时显示 -->
    <el-card
      v-if="selectedRow"
      class="sticky-card"
      :body-style="{ padding: '10px 24px' }"
    >
      <div class="sticky-info">
        <span>仿真ID：{{ selectedRow.simulation_id }}</span>
        <span>仿真名称：{{ selectedRow.name }}</span>
        <span>仿真时间：{{ selectedRow.created_at }}</span>
      </div>
    </el-card>
      <div class="env-bg" v-if="!single">
      <el-card class="env-card" :body-style="{ padding: '20px' }">
        <el-radio-group v-model="selectedOption" size="medium" class="metric-selector">
          <el-radio-button label="battery_energy">电池电量 (kWh)</el-radio-button>
          <el-radio-button label="solar_power">太阳能发电 (kWh)</el-radio-button>
          <el-radio-button label="wind_power">风力发电(kWh)</el-radio-button>
          <el-radio-button label="grid_power">国网发电(kWh)</el-radio-button>
          <el-radio-button label="total_power">总发电量 (kWh)</el-radio-button>
          <el-radio-button label="solar_cost">光能成本 (元)</el-radio-button>
          <el-radio-button label="wind_cost">风能成本 (元)</el-radio-button>
          <el-radio-button label="grid_cost">国网成本 (元)</el-radio-button>
          <el-radio-button label="solar_emission">光能碳排放 (kg CO₂/h)</el-radio-button>
          <el-radio-button label="wind_emission">风能碳排放 (kg CO₂/h)</el-radio-button>
          <el-radio-button label="grid_emission">国网碳排放 (kg CO₂/h)</el-radio-button>
        </el-radio-group>
        <span class="card-title">四种策略对比分析图</span>
        <div ref="chart" id="chart" style="width: 100%; height: 400px;" />
      </el-card>
    </div>
    </el-card>
    
   
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue'
import {
  getSimulateList,
  getSimulateDetailById,
  deleteSimulateById,
  getSimulateCategory,
  exportSimulate,
  addSimulate
} from '../api/system/simulate'
import * as XLSX from 'xlsx';
import * as echarts from 'echarts';
import { Search, Refresh ,Download} from '@element-plus/icons-vue';
import { downloadFile } from '../utils/download';
import {ElMessage, ElMessageBox} from 'element-plus';
const pageSize = 5
const total = ref(0)
const currentPage = ref(1)
const queryFormRef = ref(null);
const selectedId = ref(null);
const single = ref(true);
const selectedOption = ref('battery_energy');
const yValues = ref([]);
const timeAxis = ref([]);
const dqn_data = ref([]);
const traditional_data = ref([]);
const ppo_data = ref([]);
const a2c_data = ref([]);
const queryParams = reactive({
  page: 1,
  page_size: 5,
  keyword: null
});
const chartInstance = ref(null);

const goToScreen = (row) => {
  console.log(row, 'row');
  const params = { env_param_id: row.env_param_id, simulation_id: row.simulation_id, isHistory:true };
  const queryString = new URLSearchParams(params).toString();

  //TODO 需要修改为大屏端口
  const url = `http://localhost:8080?${queryString}`;
  window.open(url, '_blank');
}

const deleteSimulate = (row) => {
  ElMessageBox.confirm('确认删除该仿真记录吗？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
    deleteSimulateById(row.simulation_id).then(() => {
      ElMessage.success('删除成功');
      getSimulateList(queryParams).then(res => {
        tableData.value = res.data.data.items;
        tableData.value.forEach(item => {
          item.created_at = item.created_at.split('T')[0]
        })
        total.value = res.data.data.total;
        console.log(total.value, 'total');
      })
    })
  }).catch(() => {});
}
watch(selectedOption, () => {
  updateChart();
})
watch(currentPage, () => {
  queryParams.page = currentPage.value;
  getSimulateList(queryParams).then(res => {
    tableData.value = res.data.data.items;
    tableData.value.forEach(item => {
      item.created_at = item.created_at.split('T')[0]
    })
    total.value = res.data.data.total;
    console.log(total.value, 'total');
  })
})


//   tooltip: {
//     trigger: 'axis'
//   },
//   legend: {
//     data: ['传统策略', 'A2C算法策略', 'PPO算法策略', 'DQN算法策略']
//   },
//   grid: {
//     left: '3%',
//     right: '4%',
//     bottom: '3%',
//     containLabel: true
//   },
//   toolbox: {
//     feature: {
//       saveAsImage: {}
//     }
//   },
//   xAxis: {
//     type: 'category',
//     boundaryGap: false,
//     data: ['1', '2', '3', '4', '5', '6', '7']
//   },
//   yAxis: {
//     type: 'value'
//   },
//   series: [
//     {
//       name: '传统策略',
//       type: 'line',
//       stack: 'Total',
//       data: [120, 132, 101, 134, 90, 230, 210]
//     },
//     {
//       name: 'A2C算法策略',
//       type: 'line',
//       stack: 'Total',
//       data: [220, 182, 191, 234, 290, 330, 310]
//     },
//     {
//       name: 'PPO算法策略',
//       type: 'line',
//       stack: 'Total',
//       data: [150, 232, 201, 154, 190, 330, 410]
//     },
//     {
//       name: 'DQN算法策略',
//       type: 'line',
//       stack: 'Total',
//       data: [320, 332, 301, 334, 390, 330, 320]
//     }
//   ]
// });

// 格式化时间（图表专用）
const formatChartTime = (isoTime) => {
  if (!isoTime) return '';
  const date = new Date(isoTime);
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  return `${month}/${day} ${hour}:${minute}`;
};

const initChart = () => {
  // 获取DOM元素
  const chartDom = document.getElementById('chart');
  if (!chartDom) return;

  // 销毁已有实例
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }

  // 创建新实例
  chartInstance.value = echarts.init(chartDom);

  // 设置图表配置
  updateChart();
};

// 更新图表数据
const updateChart = () => {
  if (!chartInstance.value) return;

  // 处理数据
  const xAxisData = timeAxis.value.map(item => formatChartTime(item))
  const dqn_seriesData = dqn_data.value.map(item => [formatChartTime(item.simulation_result.time_point), item.simulation_result[selectedOption.value]])
  const traditional_seriesData = traditional_data.value.map(item => [formatChartTime(item.simulation_result.time_point), item.simulation_result[selectedOption.value]])
  const ppo_seriesData = ppo_data.value.map(item => [formatChartTime(item.simulation_result.time_point), item.simulation_result[selectedOption.value]])
  const a2c_seriesData = a2c_data.value.map(item => [formatChartTime(item.simulation_result.time_point), item.simulation_result[selectedOption.value]])


  console.log(dqn_seriesData, 'dqn_seriesData');
  // const seriesData = props.data.map(item => item.price_amount || 0);
  console.log(xAxisData, 'xxx');
  // 图表配置
  const option = {
    title: {
      // text: '四种策略对比分析'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['传统策略', 'A2C算法策略', 'PPO算法策略', 'DQN算法策略']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      boundaryGap: false,
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '传统策略',
        type: 'line',
        stack: 'Total',
        data: traditional_seriesData
      },
      {
        name: 'A2C算法策略',
        type: 'line',
        stack: 'Total',
        data: a2c_seriesData
      },
      {
        name: 'PPO算法策略',
        type: 'line',
        stack: 'Total',
        data: ppo_seriesData
      },
      {
        name: 'DQN算法策略',
        type: 'line',
        stack: 'Total',
        data: dqn_seriesData
      }
    ]
  };

  chartInstance.value.setOption(option);
};

onMounted(() => {
  getSimulateList(queryParams).then(res => {
    tableData.value = res.data.data.items;
    tableData.value.forEach(item => {
      item.created_at = item.created_at.split('T')[0]
    })
    total.value = res.data.data.total;
  })
})
const tableData = ref([])
const selectedRow = computed(() =>
  tableData.value.find(item => item.simulation_id === selectedId.value)
);
async function handleRadioClick(id) {
  single.value = false;
  if (selectedId.value === id) {
    single.value = true;
    selectedId.value = null;
  }
  await getSimulateCategoryCompare(id);
  nextTick(() => {
    initChart();
  });
}

const getSimulateCategoryCompare = async (id) => {
  const res = await getSimulateCategory(id)
  const cacheResult = res.data.data.results;
  const traditional = cacheResult.find(item => item.strategy === 'simple');
  const dqn = cacheResult.find(item => item.strategy === 'dqn');
  const ppo = cacheResult.find(item => item.strategy === 'ppo');
  const a2c = cacheResult.find(item => item.strategy === 'a2c');
  dqn_data.value = dqn.result_maps
  traditional_data.value = traditional.result_maps
  ppo_data.value = ppo.result_maps
  a2c_data.value = a2c.result_maps
  console.log(dqn_data.value, 'dqn_data');
  timeAxis.value = traditional_data.value.map(item => item.simulation_result.time_point)
  console.log(timeAxis.value, 'timeAxis');
}

const exportExcel = async () => {
  const res = await exportSimulate(selectedId.value)
  downloadFile(res.data, '历史运行数据.xlsx')
  ElMessage.success('导出成功')
}
const handleQuery = () => {
  queryParams.page = 1;
  queryParams.page_size = 5;
  getSimulateList(queryParams).then(res => {
    tableData.value = res.data.data.items;
    tableData.value.forEach(item => {
      item.created_at = item.created_at.split('T')[0]
    })
    total.value = res.data.data.total;
  })
}
const resetQuery = () => {
  queryParams.keyword = null;
  queryFormRef.value?.resetFields();
}
</script>

<style scoped>
.env-bg {
  min-height: 100%;
  background-color: #f9fbfd;
  color: #222;
  font-family: Arial, sans-serif;
  padding: 20px 0;
  overflow: hidden;
}

.env-card {
  background: #ffffff;
  border-radius: 10px;
  border: 0.5px solid #d1d7dc;
  margin: 20px auto;

  max-width: 1200px;
}

.card-title {
  font-size: 20px;
  font-weight: bold;
  color: #1976d2;
  display: block;
  margin-bottom: 20px;
}

.export-btn {
  border-radius: 8px;
  padding: 10px 24px;
  font-weight: 600;
  font-size: 15px;
  background: linear-gradient(135deg, #1976d2 0%, #42a5f5 100%);
  color: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(25, 118, 210, 0.12);
  margin-top: 20px;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}
.export-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #1565c0 0%, #1976d2 100%);
  color: #fff;
  box-shadow: 0 4px 16px rgba(25, 118, 210, 0.18);
  transform: translateY(-2px);
}
.export-btn:disabled {
  background: #e0e0e0 !important;
  color: #aaa !important;
  cursor: not-allowed !important;
  box-shadow: none !important;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

/* 指标切换按钮组整体居中 */
.metric-selector {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  margin-bottom: 18px;
  gap: 10px;
  background: #f8fafc;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(90, 150, 255, 0.08);
  padding: 10px 18px;
}

/* 单个按钮美化 */
:deep(.metric-selector .el-radio-button__inner) {
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px !important;
  background: #f5f7fa;
  color: #000000;
  font-size: 15px;
  font-weight: 500;
  border: 1.5px solid #e3eaf1;   /* 新增：浅色边框 */
  margin: 0 6px;
  min-width: 120px;
  min-height: 38px;
  line-height: 38px;
  transition: background 0.2s, color 0.2s, border 0.2s;
  box-shadow: none;
  padding: 0 16px;
}

/* 选中按钮 */
:deep(.metric-selector .el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background: linear-gradient(90deg, #1976d2 0%, #42a5f5 100%);
  color: #fff;
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(90, 150, 255, 0.12);
  border: 1.5px solid #1976d2; /* 选中时边框更明显 */
}

/* 悬浮按钮 */
:deep(.metric-selector .el-radio-button__inner:hover) {
  background: #e3f2fd;
  color: #1976d2;
  border: 1.5px solid #90caf9; /* 悬浮时边框变蓝 */
}

.sticky-card {
  position: sticky;
  z-index: 10;
  margin-top: 30px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(90, 150, 255, 0.08);
  background: #fff;
}

.sticky-info {
  display: flex;
  gap: 32px;
  font-size: 16px;
  color: #000000;
  font-weight: 500;
  align-items: center;
}
</style>
